#include <iostream>
#include <stdlib.h>
#include <algorithm>

#include "libmri.h"

using namespace std;

int main (int argc, char **argv)
{
	shm_array_t *shm_calib = 0, *shm_k = 0, *shm_output = 0;
	char *output = 0;

	if (0 == shm_calib){
		if (get_shm_array("calib", &shm_calib)){
			perror("calib");
			return -1;
		}
	}

	if (0 == shm_k){
		if (get_shm_array("k", &shm_k)){
			perror("k");
			return -1;
		}
	}

	if (0 == output){
		output = strdup("output");
	}

	if (make_shm_array (output, shm_k, &shm_output)){
		perror(output);
		return -1;
	}

	int csize[4] = {shm_calib->dims[0], shm_calib->dims[1],
	                shm_calib->dims[2], shm_calib->dims[3]};

	cplxf *calib; cuda (Malloc (&calib,sizeof(*calib) *
	                            csize[0]*csize[1]*csize[2]*csize[3]));
	cuda (Memcpy(calib, shm_calib->data.c,
	             sizeof(*calib) * csize[0]*csize[1]*csize[2]*csize[3],
	             cudaMemcpyHostToDevice));


	int ksize[3] = {shm_k->dims[0], shm_k->dims[1], shm_k->dims[2]};

	cplxf *k; cuda (Malloc(&k, sizeof(*k)*ksize[0]*ksize[1]*ksize[2]*csize[3]));
	cuda (Memcpy (k, shm_k->data.c,
	              sizeof(*k)*ksize[0]*ksize[1]*ksize[2]*csize[3],
	              cudaMemcpyHostToDevice));


	cplxf *z; cuda (Malloc(&z, sizeof(*k)*ksize[0]*ksize[1]*ksize[2]*csize[3]));

	calib3d_cuatamul (z, calib, csize, k, ksize);

	cuda (ThreadSynchronize());

	cuda (Memcpy (shm_output->data.c, z,
	              sizeof(*k)*ksize[0]*ksize[1]*ksize[2]*csize[3],
	              cudaMemcpyDeviceToHost));

	return 0;
}
